<html>
<head>
    <title>LocalPix</title>
    <script type="text/javascript" src="/js/jquery.js"></script>
    <script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAAT1uo0SSkJNXzR5BVm3lBZxQLdBQDC_WNldTFMeuLnkYTj9lLcRQ5j1l-mfA0XT1B_7UwbRgPXx8LOw" type="text/javascript"></script>

    <script type="text/javascript">
        var map;
        $(document).ready(function() {
            map = new GMap2($('#map').get(0));
            map.addControl(new GSmallZoomControl());

            //
            // this event fires whenever the map is done moving or zooming
            //
            GEvent.addListener(map, "moveend", mapMoved);

            $('#addressForm input:button').bind('click',function() {
                var addr = $('#address').val();
                console.log('geocoding address: ' +addr);
                geocodeAddress(addr, function(lat, lng, address) {
                    // show result from geocode on page
                    $('#geocodeResult').html('lat: ' + lat + ' lng: ' + lng + ' address: ' + address);

                    // set map center (fires "moveend" event)
                    map.setCenter(new GLatLng(lat, lng), 17);
                });
            });
        });

        /*
        * when the google map changes boundries it fires an event,
        * this is the handler for that event.
        */
        function mapMoved() {
            // get map bounding box
            var swCorner = map.getBounds().getSouthWest();
            var neCorner = map.getBounds().getNorthEast();
            var bbox = swCorner.lng() + ',' + swCorner.lat()+',' + neCorner.lng() + ',' + neCorner.lat();
            console.log(bbox);
        }

        /*
         * geocode the address and call the passed callback method with the important bits.
         *
         * @param address  - String "1600 Pennsylvania Avenue NW Washington, DC 20500"
         * @param callback - function to call with result of geocode - function(String latitude,String longitude,String address) {}
         */
        function geocodeAddress(address, callback) {
            $.get('/proxy.jsp', {url: 'http://rpc.geocoder.us/service/csv?address=' + encodeURIComponent(address)}, function(response) {
                // we get a CSV from this service lat,lng,address
                var lat = response.split(',')[0];
                var lng = response.split(',')[1];
                var addr = response.split(',')[2];

                callback(lat, lng, addr);
            }, 'TEXT');
        }
    </script>
</head>
<body>
<form id="addressForm">
    <input id="address" size="50" value="1600 Pennsylvania Avenue NW Washington, DC 20500"/>
    <input type="button" value="geocode"/>
</form>

<div id="geocodeResult"></div>
<div id="map" style="width: 600px; height: 400px"></div>

</body>
</html>

